package quoridor;

import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * A Class that has static methods for converting particles of Glendennings Strings
 * and a continuous method for parsing an entire String.
 * Exists to shift moves from string form to program-internal (Move Object) and
 * vice versa.
 * @author Jono
 *
 */
public class Converter
{
	private Scanner sc;
	private int moveNumber;
    
    public Converter(String gameString) {
    	sc = new Scanner(gameString);
    	moveNumber = 0;
    }
    
    public Move getNextMove() {
    	PlayerColour playerColour;
    	Move nextMove;
    	
    	if (moveNumber % 2 == 0) {
    		playerColour = PlayerColour.BLACK;
    	} else {
    		playerColour = PlayerColour.WHITE;
    	}
    	
    	moveNumber++;
    	
    	try {
    		String tmpString = sc.next();
    		nextMove = stringToMove(tmpString, playerColour);
    	} catch (NoSuchElementException e) {
    		nextMove = null;
    	}
    	
		return nextMove;
    }
    
    public static Move stringToMove(String in, PlayerColour player)
    {
        in.replaceAll("\\s", "");
        in.toLowerCase();
        char col = in.charAt(0);
        char row = in.charAt(1);
        char orientation = 0;
        if (in.length() == 3)
        {
            orientation = in.charAt(2);
        }
        int colNum = (col - 'a');
        int rowNum = (row - '1');
        Coordinate newTarget = new QuoridorCoordinate(rowNum, colNum);
        int newType = 0;
        if (in.length() == 3)
        {
            if (orientation == 'v')
                newType = 1;
            else if (orientation == 'h')
                newType = 2;
        }
        else newType = 0;
        
        Move toReturn = new QuoridorMove(newTarget, newType, player);
        return toReturn;
    }
    
    public static String moveToString(QuoridorMove in)
    {
        int rowNum = in.getCoordinate().getRow();
        int colNum = in.getCoordinate().getColumn();
        char row = (char) (rowNum + '1');
        char col = (char) (colNum + 'a');
        String toReturn = null;
        if (in.getType() == 0)
        {
            toReturn = Character.toString(col)+Character.toString(row);
        }
        else if (in.getType() == 1)
        {
            toReturn = Character.toString(col)+Character.toString(row)+"v";
        }
        else if (in.getType() == 2)
        {
            toReturn = Character.toString(col)+Character.toString(row)+"h";
        }
        return toReturn;
    }
}
